package book.items.item15;

public class Complex {
	// stores real part of complex number
	private final double re; 
	// store imaginary part of complex number
	private final double im;
	
	private Complex(double re, double im) {
		this.re = re;
		this.im = im;
	}
	
	public static Complex valueOf(double re, double im) {
		return new Complex(re, im);
	}
	
	public Complex add(Complex c){
		return new Complex(re + c.re, im + c.im);
	}

	@Override
	public boolean equals(Object o) {
		if(o == this){
			return true;
		}
		if(!(o instanceof Complex)) {
			return false;
		}
		Complex that = (Complex) o;
		if(Double.compare(this.re, that.re) == 0 && 
				Double.compare(this.im, that.im) == 0) {
			return true;
		}
		return false;
	}

	@Override
	public int hashCode() {
		int result = 17 + hashDouble(re);
		result = 31 * result + hashDouble(im);
		return result;
	}
	
	private static int hashDouble(double val){
		long longBits = Double.doubleToLongBits(val);
		return (int) (longBits ^ (longBits >>> 32));
	}

	@Override
	public String toString() {
		return "(" + this.re + " + " +this.im + "j)";
	}
}
